package org.linlinjava.litemall.admin.web.order_manage;

import cn.com.ejiakanghu.core.exception.CheckException;
import cn.com.ejiakanghu.service.OrderService;
import io.swagger.models.auth.In;
import org.linlinjava.litemall.admin.constant.HeaderConstant;
import org.linlinjava.litemall.admin.service.order_manage.AgedMallOrderService;
import org.linlinjava.litemall.admin.vo.order_manage.OrderSettingVo;
import org.linlinjava.litemall.core.tool.wxpayscore.WxPayScoreTool;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallOrderItem;
import org.linlinjava.litemall.db.service.AgedmallWxNoDepositService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.util.PromoteOrderGoodsType;
import org.linlinjava.litemall.db.vo.order_manage.NotTakeReturnForm;
import org.linlinjava.litemall.db.vo.order_manage.OrderBuyOutForm;
import org.linlinjava.litemall.db.vo.order_manage.OrderPriceAndFreight;
import org.linlinjava.litemall.db.vo.order_manage.SettledUpdatePriceVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class AgedMallOrder2Controller {
    private final Logger logger = LoggerFactory.getLogger(AgedMallOrder2Controller.class);
    @Autowired
    private AgedMallOrderService agedMallOrderService;
    @Autowired
    private LitemallOrderService litemallOrderService;
    @Autowired
    private OrderService orderService;

    /**
     * 获取租售订单列表
     */
    @PostMapping("/rentOrderList")
    public Object rentOrderList(@RequestParam(required = false) String phone,
                                @RequestParam(required = false) String orderSn,
                                @RequestParam(required = false) Integer state,
                                @RequestParam(required = false) Integer provinceId,
                                @RequestParam(required = false) Integer cityId,
                                @RequestParam(required = false) Integer storeId,
                                @RequestParam(required = false) LocalDateTime startTime,
                                @RequestParam(required = false) LocalDateTime endTime,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer limit,
                                HttpServletRequest request) {
        Integer busiId = request.getIntHeader(HeaderConstant.HEADER_BUSIID);
        if (busiId == -1) {
            return ResponseUtil.unauthz();
        }
        return agedMallOrderService.rentOrderList(phone, orderSn, state, provinceId, cityId, storeId,startTime, endTime, busiId, page, limit);
    }

    /**
     * 根据不同的订单状态加载订单详情页
     */
    @PostMapping("/rentOrderDetail")
    public Object rentOrderDetail(@RequestParam Integer orderId, Integer bigOrderId,
                                  @RequestParam Integer state) {
        return agedMallOrderService.rentOrderDetail(orderId, state , bigOrderId);
    }

    /**
     * 待发货状态下的订单点击去发货或者待发货状态下修改包裹信息
     */
    @PostMapping("/notDeliver/load")
    public Object notDeliverLoad(@RequestParam Integer orderId, @RequestParam(required = false) Integer packId) {
        return agedMallOrderService.notDeliverLoad(orderId, packId);
    }


    /**
     * 待发货-确认发货 打包
     *
     * @param orderId        子订单id
     * @param packId 包裹id（编辑时）
     * @param deliveryType 发货方式 1门店 2 物流 3自提
     * @param deliveryUserId 配送员id （id为all为全部一起抢单，id为sort为按顺序抢单，其他数字为具体的配送员id）
     * @param shipId 快递公司Id
     * @param shipSn 快递单号
     * @param packUserId 配货员id （id为all为全部一起抢单，id为sort为按顺序抢单，其他数字为具体的配货员id）
     * @param isPickUpSelf   是否自提 0表示自提1表示非自提
     * @return
     */
    @PostMapping("/notDeliver/sureDelivery")
    public Object notDeliverSureDelivery(
            Integer orderId,
            String packId,
            Integer deliveryType,
            String deliveryUserId,
            String shipId,
            String shipSn,
            String packUserId,
            int isPickUpSelf) {
        try {
            return agedMallOrderService.notDeliverSureDelivery(orderId, packId, deliveryType, deliveryUserId, shipId, shipSn, packUserId, isPickUpSelf);
        } catch (CheckException e) {
        }
        return ResponseUtil.fail();
    }

    /**
     * 点击取消订单按钮弹出弹窗，确认后订单变更为已关闭状态，后台退货退款
     */
    @PostMapping("/cancelOrder")
    public Object cancelOrder(@RequestParam Integer id, String reason) {
        LitemallOrder litemallOrder = litemallOrderService.findById(id);
        return orderService.cancel(litemallOrder, reason);
    }

    /**
     * 管理系统帮助用户确认收货
     * @param id 子订单id
     * @return
     */
    @PostMapping("/confirmReceiptNormal")
    public Object confirmReceiptNormal(@RequestParam Integer id) {
        logger.debug("系统帮助用户确认收货: 子订单ID:{}",id);
        LitemallOrderItem orderItem = litemallOrderService.findItemById(id);
        return orderService.confirmReceiptNormal(orderItem,false);
    }


    /**
     * 待用户自提状态下的订单点击取货
     */
    @PostMapping("/notTakingByself/load")
    public Object notTakingByselfLoad(@RequestParam Integer orderId) {
        return agedMallOrderService.notTakingByselfLoad(orderId);
    }

    /**
     * 待用户自提-确认已收货 订单商品状态变更（租赁为使用中/售卖为已完成）
     * @param orderId 子订单id
     */
    @PostMapping("/notTakingByself/taked")
    public Object notTakingByselfTaked(@RequestParam Integer orderId) {
        List<Integer> ids = new ArrayList<>();
        ids.add(orderId);
        return agedMallOrderService.notTakingByselfTaked(ids);
    }

    /**
     * 待用户收货-确认已收货 订单商品状态变更（租赁为使用者/售卖为已完成）
     */
    @PostMapping("/notTake/taked")
    public Object notTakeTaked(@RequestParam Integer id) {
        return agedMallOrderService.notTakeTaked(id);
    }

    /**
     * 待收货状态下的订单点击退货/退款
     */
    @PostMapping("/notTake/returnLoad")
    public Object notTakeReturnLoad(@RequestParam Integer orderId) {
        return agedMallOrderService.notTakeReturnLoad(orderId);
    }

    /**
     * 待收货-退货/退款/换货 订单商品状态变更（退货、退款确认后商品状态变更为售后的待商户处理）  returnRefundAndExchangeType
     */
    @PostMapping("/notTake/return")
    public Object notTakeReturn(@RequestBody NotTakeReturnForm notTakeReturnForm) {
        return agedMallOrderService.notTakeReturn(notTakeReturnForm);
    }

    /**
     * 使用中状态下的商品列表
     */
    @PostMapping("/using/returnLoad")
    public Object usingReturnLoad(@RequestParam Integer orderId) {
        return agedMallOrderService.usingReturnLoad(orderId);
    }

    /**
     * 使用中-归还 订单商品状态变更
     */
    @PostMapping("/using/return")
    public Object usingReturn(@RequestParam Integer id,
                              @RequestParam List<Integer> orderIds,
                              @RequestParam Integer ship,
                              @RequestParam(required = false) String deliveryManId,
                              @RequestParam(required = false) String maintainId,
                              @RequestParam(required = false) String expressCompany,
                              @RequestParam(required = false) String expressCode) {
        return agedMallOrderService.usingReturn(id, orderIds, ship, deliveryManId, maintainId, expressCompany, expressCode);
    }


    /**
     * 使用中-买断 订单商品状态变更（商品类型变更为出售，若租赁押金金额足够，则扣除押金中的商品金额，归还剩余押金金额，若押金金额不够，则扣除押金，订单商品转化为待用户结算）
     *
     * @param orderBuyOutForm
     * @return
     */
    @PostMapping("/using/buyOut")
    public Object usingBuyOut(@RequestBody OrderBuyOutForm orderBuyOutForm) {
        return agedMallOrderService.usingBuyOut(orderBuyOutForm);
    }

    /**
     * 待取货状态下的商品列表
     */
    @PostMapping("/notPickUp/load")
    public Object notPickUpLoad(@RequestParam Integer orderId) {
        return agedMallOrderService.notPickUpLoad(orderId);
    }

    /**
     * 待取货-取货 订单商品状态变更
     */
    @PostMapping("/notPickUp/pickUp")
    public Object notPickUpPickUp(@RequestParam Integer id,
                                  @RequestParam List<Integer> ordergoodsId,
                                  @RequestParam Integer ship,
                                  @RequestParam(required = false) String deliveryManId,
                                  @RequestParam(required = false) String expressCompany,
                                  @RequestParam(required = false) String expressCode,
                                  @RequestParam(required = false) String maintainManId) {
        return agedMallOrderService.notPickUpPickUp(id, ordergoodsId, ship, deliveryManId, expressCompany, expressCode, maintainManId);
    }

    /**
     * 待商户收货-取货 订单商品状态变更
     */
    @PostMapping("/notTakingByBusiness/take")
    public Object notTakingByBusinessTake(@RequestParam Integer id,
                                          @RequestParam List<Integer> orderIds,
                                          @RequestParam String deliveryManId,
                                          @RequestParam String maintainManId,
                                          @RequestParam Integer ship,
                                          @RequestParam String expressCompany,
                                          @RequestParam String expressCode) {
        return agedMallOrderService.notTakingByBusinessTake(id, orderIds, deliveryManId, maintainManId, ship,expressCompany,expressCode);
    }

    /**
     * 取消包裹-重新进行商品打包
     */
    @PostMapping("/cancelPack")
    public Object cancelPack(Integer id) {
        return agedMallOrderService.cancelPack(id);
    }

    /**
     * 订单设置
     */
    @GetMapping("/orderSetting")
    public Object orderSetting(@Validated OrderSettingVo orderSettingVo) {
        return agedMallOrderService.orderSetting(orderSettingVo);
    }

    /**
     * 获取订单设置
     */
    @GetMapping("/getOrderSetting")
    public Object getOrderSetting(Integer shopId) {
        return agedMallOrderService.getOrderSetting(shopId);
    }

    @PostMapping("/using/buyOutLoad")
    public Object usingBuyOutLoad(Integer orderId) {
        return agedMallOrderService.usingBuyOutLoad(orderId);
    }

    /**
     * 归还完成
     */
    @PostMapping("/returnCompleteEvent/{id}")
    public Object returnCompleteEvent(@PathVariable Integer id) {
        return agedMallOrderService.returnCompleteEvent(id);
    }


    @PostMapping("/getSubOrderAndGoodsInformation")
    public Object getSubOrderAndGoodsInformation(@RequestParam("orderItemId") int orderItemId) {
        return agedMallOrderService.getSubOrderAndGoodsInformation(orderItemId);
    }

    /**
     * 修改订单的运费和商品的单价
     *
     * @param orderPriceAndFreight 前端传递的参数的包装类型
     * @return
     */
    @PostMapping("/updatePriceAndFreight")
    public Object updatePriceAndFreight(@RequestBody OrderPriceAndFreight orderPriceAndFreight) {
        return agedMallOrderService.updatePriceAndFreight(orderPriceAndFreight);
    }

    /**
     * /notDeliver/packBySelf
     * 用户选择自提的待发货状态下的订单点击选择配货人之后状态变更为待用户自提状态
     *
     * @param orderId    订单id
     * @param packUserId 配货员id
     * @return
     */
    @PostMapping("/notDeliver/packBySelf")
    public Object packBySelf(Integer orderId, String packUserId) {
        return agedMallOrderService.packUserId(orderId, packUserId);
    }

    /**
     * /notTakingByself/take  待用户自提状态下的订单点击已取货
     *
     * @param orderId
     * @param pickId
     * @return
     */
    @PostMapping("/notTakingByself/take")
    public Object take(Integer orderId, Integer pickId) {
        return agedMallOrderService.take(orderId, pickId);
    }



    @PostMapping("/toBeSettledUpdatePrice")
    public Object toBeSettledUpdatePrice(@RequestBody SettledUpdatePriceVo settledUpdatePriceVo){
        return agedMallOrderService.toBeSettledUpdatePrice(settledUpdatePriceVo);
    }

    /**
     * 更新子订单的状态
     * @param childOrderCode
     * @param status 后端传递的状态码,801直接对应402，401直接对应404
     * @return
     */
    @RequestMapping("/updateChildOrderStatus")
    public Object updateChildOrderStatus(String childOrderCode, int status, String reason) {
        List<LitemallOrderItem> orderItemList = litemallOrderService.sbuOrderListByChildOrderCode(childOrderCode);
        boolean isLease = PromoteOrderGoodsType.GOODS_TYPE_LEASE.equals(orderItemList.get(0).getGoodsType());
        status = OrderUtil.getChildSysStatByAdminPageStat((short) status, isLease);
        int rst = agedMallOrderService.updateChildOrderStatus(childOrderCode, status);
        if(rst > 0) {
            boolean isCancelOrder = OrderUtil.adminIsCancelOrder(status);
            if(isCancelOrder) {
                //选择取消订单，免押订单进行免押取消
                orderService.cancelWxNoDepositByChildOrderCode(childOrderCode, reason);
            }
        }
        return rst > 0 ? ResponseUtil.ok() : ResponseUtil.fail("更新失败");
    }

}
